import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

abstract class PageState<Pa extends RoutePage> extends ConsumerState<Pa> with RouteAware, WidgetsBindingObserver {
  PageState() {
    WidgetsBinding.instance.addObserver(this);
  }

  bool get keepRouteObserver => true;

  @override
  @mustCallSuper
  void initState() {
    SchedulerBinding.instance.addPostFrameCallback((_) {
      didPageLoad();
    });
    super.initState();
  }

  @override
  @mustCallSuper
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  void didPageLoad() {}

  @override
  @mustCallSuper
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  @mustCallSuper
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive:
        onInActive();
        break;
      case AppLifecycleState.paused:
        onPaused();
        break;
      case AppLifecycleState.resumed:
        onResumed();
        break;
      case AppLifecycleState.detached:
        onDetached();
        break;
      case AppLifecycleState.hidden:
        onHidden();
        break;
    }
  }

  /// Called when the application is in an inactive state and is not receiving user input.
  /// On iOS, this state corresponds to an app or the Flutter host view running in
  /// the foreground inactive state. Apps transition to this state when in a phone call,
  /// responding to a TouchID request, when entering the app switcher or the control center,
  /// or when the UIViewController hosting the Flutter app is transitioning.
  /// On Android, this corresponds to an app or the Flutter host view running in
  /// the foreground inactive state. Apps transition to this state when another
  /// activity is focused, such as a split-screen app, a phone call, a
  /// picture-in-picture app, a system dialog, or another window.
  void onInActive() {}

  /// Called when the application is not currently visible to the user, not responding to user input, and running in the background.
  void onPaused() {}

  /// Called when the application is visible and is responding to the user i.e. in the foreground and running.
  void onResumed() {}

  /// Called before the application is detached.
  void onDetached() {}
  void onHidden() {}
}

abstract class RoutePage extends ConsumerStatefulWidget {
  const RoutePage({Key? key}) : super(key: key);
}
